# Copyright 2010-2015 RethinkDB

JAVA_SRC_DIR=$(TOP)/drivers/java
JAVA_BUILD_DIR=$(TOP)/build/drivers/java
JAVA_PKG_DIR=$(TOP)/build/package/java

JAVA_PACKAGE_DIR=$(JAVA_SRC_DIR)/src/main/java/com/rethinkdb

JAVA_GEN_DIR=$(JAVA_PACKAGE_DIR)/gen
JAVA_PROTO_DIR=$(JAVA_GEN_DIR)/proto
JAVA_AST_DIR=$(JAVA_GEN_DIR)/ast
JAVA_MODEL_DIR=$(JAVA_GEN_DIR)/model
JAVA_EXC_DIR=$(JAVA_GEN_DIR)/exc
JAVA_TEST_DIR=$(JAVA_SRC_DIR)/src/test/java/com/rethinkdb
JAVA_TEST_GEN_DIR=$(JAVA_TEST_DIR)/gen

METAJAVA=$(JAVA_SRC_DIR)/metajava.py
JAVA_CONVERT_PROTO=$(JAVA_SRC_DIR)/convert_protofile.py
JAVA_CONVERT_TESTS=$(JAVA_SRC_DIR)/convert_tests.py

JAVA_TEMPLATE_DIR=$(JAVA_SRC_DIR)/templates
JAVA_PROTO_FILE=$(TOP)/src/rdb_protocol/ql2.proto
JAVA_PROTO_JSON=$(JAVA_BUILD_DIR)/proto_basic.json
JAVA_TERM_INFO=$(JAVA_SRC_DIR)/term_info.json
JAVA_JAVA_TERM_INFO=$(JAVA_BUILD_DIR)/java_term_info.json
JAVA_GLOBAL_INFO=$(JAVA_SRC_DIR)/global_info.json

GRADLE=gradle --build-file=$(JAVA_SRC_DIR)/build.gradle       \
	      --settings-file=$(JAVA_SRC_DIR)/settings.gradle \
	      --quiet

.PHONY: java-driver
java-driver: | $(JAVA_BUILD_DIR)/.
	$P GRADLE ASSEMBLING JAVA DRIVER
	$(GRADLE) assemble

.PHONY: java-clean
java-clean:
	$P CLEAN
	$(GRADLE) clean
	rm -rf $(JAVA_BUILD_DIR)

.PHONY: clean-autogenerated
# this deletes all generated files, even ones checked into git
clean-autogenerated: | java-clean
	$P SUPER-CLEAN
	rm -rf $(JAVA_GEN_DIR)/*
	rm -rf $(JAVA_TEST_GEN_DIR)/*

.PHONY: java-convert-tests
java-convert-tests: | py-driver java-driver
	$P CONVERT JAVA TESTS
	$(JAVA_CONVERT_TESTS) \
	    --test-dir=$(TOP)/test/rql_test/src             \
	    --python-driver-dir=$(TOP)/build/drivers/python \
	    --test-output-dir=$(JAVA_TEST_GEN_DIR)          \
	    --template-dir=$(JAVA_TEMPLATE_DIR)

.PHONY: java-test
java-test: | java-convert-tests
	$P JAVA DRIVER TESTS
	$(GRADLE) test

$(JAVA_PROTO_JSON): $(JAVA_PROTO_FILE) $(JAVA_CONVERT_PROTO)
	$P CONVERT
	$(PYTHON) $(JAVA_CONVERT_PROTO) $(JAVA_PROTO_FILE) $(JAVA_PROTO_JSON)

$(JAVA_TERM_INFO): $(JAVA_PROTO_JSON) $(METAJAVA)
	$P UPDATING $(notdir $@)
	$(PYTHON) $(METAJAVA) update-terminfo	\
		--term-info=$(JAVA_TERM_INFO)	\
		--proto-json=$(JAVA_PROTO_JSON)

$(JAVA_JAVA_TERM_INFO): $(JAVA_TERM_INFO) $(METAJAVA) | $(JAVA_BUILD_DIR)/.
	$P GENERATING
	$(PYTHON) $(METAJAVA) generate-java-terminfo	\
		--term-info=$(JAVA_TERM_INFO)		\
		--output-file=$@

.PHONY: update-driver
# This generates source files needed for the driver. Should be fairly
# autonomous, but may need some manual intervention in some cases.
update-driver: $(JAVA_JAVA_TERM_INFO) $(JAVA_GLOBAL_INFO) $(METAJAVA) \
	| $(JAVA_MODEL_DIR) $(JAVA_AST_DIR) $(JAVA_PROTO_DIR) $(JAVA_EXC_DIR)
	$P GENERATING JAVA CLASSES
	$(PYTHON) $(METAJAVA) generate-java-classes	\
		--global-info=$(JAVA_GLOBAL_INFO)       \
		--proto-json=$(JAVA_PROTO_JSON)		\
		--java-term-info=$(JAVA_JAVA_TERM_INFO)	\
		--template-dir=$(JAVA_TEMPLATE_DIR)     \
		--package-dir=$(JAVA_PACKAGE_DIR)
